import store from './store'
import router from './router'
import asyncRoutes from './router/asyncRoutes'

function getFirstRoutePromission (permission) {
  const firstPromArr = permission.map(item => {
    return item.split(':')[0]
  })
  return Array.from(new Set(firstPromArr))
}

function getSecondRoutePromission (permission) {
  const secondPromArr = permission.map(item => {
    const arr = item.split(':')
    return `${arr[0]}:${arr[1]}`
  })
  return Array.from(new Set(secondPromArr))
}

function getRouter (firstPromission, secondPromission, asyncRoutes) {
  // 判断用户是否为管理员
  if (firstPromission.includes('*')) {
    return asyncRoutes
  }
  // 筛选出满足条件的一级路由
  const firstRoutes = asyncRoutes.filter(item => {
    return firstPromission.includes(item.permission)
  })
  // 筛选出满足条件的二级路由
  const secondRoutes = firstRoutes.map(item => {
    return {
      ...item,
      children: item.children.filter(item =>
        secondPromission.includes(item.permission)
      )
    }
  })
  return secondRoutes
}

const whiteList = ['/login', '/404']
router.beforeEach(async (to, form, next) => {
  const token = store.state.user.token
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      next()
      // 1. 拿到用户的权限标识
      const promission = await store.dispatch('menu/getPromission')
      console.log('全部的权限标识', promission)
      // 2. 筛选中一级路由对应的权限标识
      const firstPromission = getFirstRoutePromission(promission)
      // console.log('获取一级路由对应的权限标识', firstPromission)
      // 3. 筛选中一级路由对应的权限标识
      const secondPromission = getSecondRoutePromission(promission)
      // console.log('获取二级路由对应的权限标识', secondPromission)
      // 4. 根据一级权限标识和二级权限标识和动态路由进行筛选
      const routes = getRouter(firstPromission, secondPromission, asyncRoutes)
      // console.log('动态路由', routes)
      // 5. 把筛选后的路由展示到左侧
      //  5.1 先把筛选之后的路由添加到路由对象中(跳转)
      routes.forEach(item => router.addRoute(item))
      //  5.2 再把筛选之后的路由添加到vuex在(渲染)
      store.commit('menu/setMenuList', routes)
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
